package com.letv.so.servlet;

import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.letv.so.bean.ExtranetAlbumBean;
import com.letv.so.bean.PlayingVideoBean;
import com.letv.so.bean.VideoBean;
import com.letv.so.constants.Constants;
import com.letv.so.constants.Mappings;
import com.letv.so.util.StringUtil;
import com.letv.so.util.ThreadLocalUtil;

/**
 * 全局视频ID接口
 * 
 * @time 2014-09-28
 * @author HaiChuanLiu
 * 
 */
public class QueryCbaseVidServlet extends AbstractQueryDataServlet {
    
    private static final long serialVersionUID = -5850143289714797925L;

    private Logger logger = Logger.getLogger(QueryCbaseVidServlet.class);

    private final static String DEFAULT_RESULT = "{}";
    
    private String getLesoAid(String id, String src) {
		String lesoAid = "";
		if (Constants.SRC_VRS.equals(src)) { // sokey如果对应的是vrs的专辑需要一次查询，才能获得lesoAid
			String soKey = "newleso_la_" + id;
			String soData = queryDataService.get(soKey);
			if (StringUtil.isBlank(soData)) {
				return null;
			}
			ExtranetAlbumBean eAlbum = JSON.parseObject(soData, ExtranetAlbumBean.class);
			lesoAid = eAlbum.getAid();

		} else if (Constants.SRC_LESO.equals(src)) { // sokey如果对应的是leso专辑，直接解析，即可获得lesoAid
			lesoAid = id;
		}
		return lesoAid;
	}
    /**
     * 查询相关站点信息
     */
    protected String query(Map<String, Object> rule) {
        try {
        	long starttime = System.currentTimeMillis();
            String vid = (String) rule.get("soKey");
            String subsrc = (String) rule.get("subsrc");
            String src = (String) rule.get("src");
            String sid = (String) rule.get("sid");
            logger.debug("QueryCbaseVidServlet.query vid="+vid);
            if(StringUtils.isBlank(vid)) {
                logger.warn(sid+" ,QueryCbaseVidServlet.query soKey is null");
                return DEFAULT_RESULT;
            }
            String[] segs = vid.split("_");
            if(segs == null || segs.length < 3) {
                logger.warn(sid+",QueryCbaseVidServlet.query soKey is invalid format(eg: 123456_2_2). ");
                return DEFAULT_RESULT;
            }

            List<String> dataList = null;
            String siteKey = null;
            if (StringUtils.isNotBlank(src) && Constants.SRC_VRS.equals(src)) {
	            String vrsAid = segs[0];
	            String lesoAid = getLesoAid(vrsAid,src);
	            
	            List<String> keyList = new ArrayList<String>();
	            for (String website : Mappings.WEBSITE_LIST) {
	            	if (StringUtils.isNotBlank(subsrc)) {
	            		siteKey = "newleso_ea_" + lesoAid + "_" +subsrc;
	                    keyList.add(siteKey);
	            		break;
	                }
	                siteKey = "newleso_ea_" + lesoAid + "_" +website;
	                keyList.add(siteKey);
	            }
	            dataList = queryDataService.getMulti(sid,keyList);
	            
            } else if (StringUtils.isNotBlank(src) && Constants.SRC_LESO.equals(src)) {
            	String lesoAid = segs[0];
 	            
 	            List<String> keyList = new ArrayList<String>();
 	            
 	            for (String website : Mappings.WEBSITE_LIST) {
 	            	if (StringUtils.isNotBlank(subsrc)) {
 	            		siteKey = "newleso_ea_" + lesoAid + "_" +subsrc;
 	                    keyList.add(siteKey);
 	            		break;
 	                }
 	            	siteKey = "newleso_ea_" + lesoAid + "_" +website;
 	                keyList.add(siteKey);
 	            }
 	           logger.debug(sid+" ,QueryCbaseVidServlet.query vid="+vid+", keyList="+keyList);
 	           //dataList = queryDataService.get(sid,keyList);
 	           dataList = queryDataService.getMulti(sid,keyList); 
            } else {
            	return DEFAULT_RESULT;
			}
            
            // 顺序和url的md5值
            String episode = segs[1];
            String md5Str = segs[2];
            logger.debug(sid+",QueryCbaseVidServlet.query vid="+vid+", dataList="+dataList.size());
            PlayingVideoBean bean = null;
            // 遍历所有网站的数据
            for (String data : dataList) {
                if (StringUtil.isBlank(data)) {
                    continue;
                }                
                ExtranetAlbumBean eAlbum = JSON.parseObject(data, ExtranetAlbumBean.class);
                logger.debug(sid+",QueryCbaseVidServlet.query vid eAlbum="+eAlbum);
                if (eAlbum == null || eAlbum.getVideoList() == null || eAlbum.getVideoList().size() == 0) {
                    continue;
                }
                int flag = 0;
                // 遍历专辑，全局id数据
                for(VideoBean video : eAlbum.getVideoList()) {//媒资库中排序用的是porder，作品库用的是aorder
                	logger.debug(sid+",QueryCbaseVidServlet.query vid video.getAorder()="+video.getAorder());
                    if(episode.equals(video.getAorder()) && md5Str.equals(MD5(video.getUrl()))) {
                    		bean = new PlayingVideoBean();
                    		
                    		bean.setSite(converToString(eAlbum.getSite()));
                    		
                    		bean.setPorder(video.getAorder());
                    		bean.setPlayStreams(converToString(video.getPlayStreams()));
                    		bean.setPushFlag(converToString(video.getPushFlag()));
                    		bean.setName(converToString(video.getName()));
                    		bean.setSubName(converToString(video.getSubName()));
                    		bean.setGlobalVid(vid);
                    		bean.setUrl(converToString(video.getUrl()));
                    		bean.setMid(converToString(video.getMid()));
                    		bean.setCloudId(converToString(video.getVideoPanid()));
                    		bean.setVid(converToString(video.getVid()));
                    		
                            flag = 1;
                            break;
                    }
                }
                if (flag==1) {
	                break;
                }
            }
            logger.info(sid+",QueryCbaseVidServlet, total time="+(System.currentTimeMillis()-starttime));
            String rtn =  JSON.toJSONString(bean,SerializerFeature.WriteTabAsSpecial);
            if (TRADITIONAL.contains(ThreadLocalUtil.getLang())){
                rtn = converter.convert(rtn);
            }
            return rtn;
        } catch (Exception e) {
            logger.error("QueryCbaseVidServlet.query error", e);
            return DEFAULT_RESULT;
        }
    }
    
    private String MD5(String s) {
        char hexDigits[]={'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};       
        try {
            byte[] btInput = s.getBytes();
            // 获得MD5摘要算法的 MessageDigest 对象
            MessageDigest mdInst = MessageDigest.getInstance("MD5");
            // 使用指定的字节更新摘要
            mdInst.update(btInput);
            // 获得密文
            byte[] md = mdInst.digest();
            // 把密文转换成十六进制的字符串形式
            int j = md.length;
            char str[] = new char[j * 2];
            int k = 0;
            for (int i = 0; i < j; i++) {
                byte byte0 = md[i];
                str[k++] = hexDigits[byte0 >>> 4 & 0xf];
                str[k++] = hexDigits[byte0 & 0xf];
            }
            return new String(str);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
    
    private String converToString(String value) {
    	if (StringUtils.isBlank(value)) {
	        return "";
        }else {
			return value;
		}
    }

}
